#!/bin/bash -ilex

exist=""
running=""

stop(){
  echo 'stop container: icloud'
  docker stop icloud
}

clear(){
  echo 'clear container and image: icloud'
  stop
  docker rm icloud -f
  docker rmi icloud -f
}

build(){
  echo 'build image: icloud'
  docker build -f Dockerfile -t icloud:latest .
}

init(){
  echo 'init run container: icloud'
  docker run -d -e TZ=Asia/Shanghai -p 3100:3100 --name="icloud" -v /root/lib:/root/lib -v /root/logs:/root/logs icloud:latest
}

restart(){
  echo 'check container exist & running'
  exist = `docker inspect --format '{{.Id}}' icloud`
  if [ "${exist}" == "" ]; then
    build
    sleep 1
    init
  fi
  running =`docker inspect --format '{{.State.Running}}' icloud`
  if [ "${running}" != "true" ]; then
    echo 'restart container: icloud'
    docker restart icloud
  fi
}

if [ "$1" = "clear" ]; then
clear
elif [ "$1" = "stop" ]; then
stop
elif [ "$1" = "restart" ]; then
restart
fi
